import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { Access, FormattedMessage, useAccess, useIntl, useRequest } from '@umijs/max';
import { Button, Drawer, message, TreeDataNode } from 'antd';
import { useCallback, useEffect, useRef, useState } from 'react';
import { dataResponse, roleRequestModel } from '../data';
import { deleteRole, getPermissionList, getRoleList } from '../service';
import EditForm from './EditForm';

const Rolesystem: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<dataResponse>();
  const [selectedRowsState, setSelectedRows] = useState<dataResponse[]>([]);

  const access = useAccess();
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();
  const [treeList, setTreeList] = useState<TreeDataNode[]>([]);

  const getPermission = async () => {
    const data = await getPermissionList();
    setTreeList(data);
  };

  useEffect(() => {
    getPermission()
  }, []);

  const { run: delRun, loading } = useRequest(deleteRole, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('删除成功！');
    },
    onError: () => {
      messageApi.error('删除失败，请重试！');
    },
  });

  const columns: ProColumns<dataResponse>[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      /* tooltip: 'The rule name is the unique key', */
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleDesc" defaultMessage="Description" />,
      dataIndex: 'description',
      valueType: 'textarea',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Access key="roleoption" accessible={access.canEdit('system.role')!}>
          <EditForm
            key="config"
            reload={actionRef.current?.reload}
            values={record}
            trigger={<a>修改</a>}
            treeList={treeList}
          />
        </Access>,
      ],
    },
  ];

  const handleRemove = useCallback(
    async (selectedRows: dataResponse[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');
        return;
      }
      await delRun({
        codeList: selectedRows.map((row) => row.code),
      });
    },
    [delRun],
  );

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<dataResponse, roleRequestModel>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="code"
        search={{
          labelWidth: 120,
        }}
        // 新增
        toolBarRender={() => [
          <Access key="roleoption" accessible={access.canCreate('system.role')!}>
            <EditForm
              key="create"
              reload={actionRef.current?.reload}
              trigger={
                <Button type="primary" icon={<PlusOutlined />}>
                  <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
                </Button>
              }
              treeList={treeList}
            />
          </Access>,
        ]}
        request={async (params: roleRequestModel) => {
          const msg = await getRoleList({
            name: params.name,
            pageNum: params.current,
            pageSize: params.pageSize,
          })
          return {
            data: msg.result?.items,
            total: msg.result?.totalCount,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {selectedRowsState?.length > 0 && ( // 删除按钮
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              {/* <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre , 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span> */}
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          {/* <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button> */}
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<dataResponse>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.code,
            }}
            columns={columns as ProDescriptionsItemProps<dataResponse>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default Rolesystem;
